import { _decorator, Component, Director, director, instantiate, js, Node } from 'cc';
import { BaseComponent } from '../UIManager/BaseComponent';
const { ccclass, property } = _decorator;

export class PopManager {
    private constructor() {
        // director.once(Director.EVENT_AFTER_SCENE_LAUNCH, this.Init, this);
    }

    /** 初始化方法 */
    public Init(): void {
        this.Root = director.getScene().getChildByName('Canvas').getChildByName("PopManager");
        this.NoTouch = this.Root.getChildByName("NoTouch");
        this.NoTouch.active = false;

        console.log(this.NoTouch)
    }

    /** 单例实例 */
    public static readonly instance: PopManager = new PopManager();

    //场景节点
    private Root: Node = null;

    //禁止点击背景
    private NoTouch: Node = null;

    //已添加弹窗列表
    private PopList: Map<string, BaseComponent> = new Map();

    //当前场景
    public CurrentPop: BaseComponent | null = null;

    /**
     * 显示弹窗
     * @param 类名称
     */
    public ShowPop(_classname: string, _istouch: boolean = true) {

        this.NoTouch.active = _istouch;

        let view: BaseComponent = this.PopList.get(_classname);
        const UIClass = js.getClassByName(_classname) as { new(): BaseComponent };

        if (!view) {
            const node: Node = instantiate(app.resManager.Prefabs[_classname]);
            view = node.getComponent(UIClass);
            this.PopList.set(_classname, view);
        }

        //如果有场景则隐藏掉
        if (this.CurrentPop) {
            this.CurrentPop.node.removeFromParent();
        }

        this.CurrentPop = view;

        console.log(this.CurrentPop, _classname)

        this.CurrentPop.node.parent = this.Root;
        this.CurrentPop.node.setSiblingIndex(this.Root.children.length - 1);

    }

    /**
     * 隐藏弹窗
     */
    public HidePop(_classname: string) {
        this.NoTouch.active = false;
        let view: BaseComponent = this.PopList.get(_classname);
        if (view) {
            view.node.removeFromParent();
        }
    }

}

/** 导出单例实例 */
export const popManager = PopManager.instance;


